package designpattern.proxy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class WomanSpeechDelegate implements ISpeech {
	private WomenSpeech woman;

	public WomanSpeechDelegate(WomenSpeech woman) {
		this.woman = woman;
	}

	@Override
	public void makeSpeech() {
		InvocationHandler handler = new InvocationHandler() {

			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				woman.saySomething();
				System.out.println("I m a delegate!");
				return null;
			}
		};
		
		// 通过 Proxy 直接创建动态代理类实例
		ISpeech proxy = (ISpeech)Proxy.newProxyInstance( woman.getClass().getClassLoader(), 
			 new Class[] { ISpeech.class }, 
			 handler ); 
/*
		Class clazz = Proxy.getProxyClass(woman.getClass().getClassLoader(),
				new Class[] { ISpeech.class });

		Constructor constructor;
		try {
			constructor = clazz
					.getConstructor(new Class[] { InvocationHandler.class });
			ISpeech proxy = (ISpeech) constructor
					.newInstance(new Object[] { handler });
			
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
*/
		proxy.makeSpeech();
	}

}
